# -*- coding: utf-8 -*-

import time
import hashlib
import requests
import urllib
import copy
import operator
import json
import hmac
import binascii

#每2秒6个请求


class Bihe():
    
    _headers = {
    'Content-Type': 'application/json; charset=utf-8',
    'X-BIBR-APIKEY':'0e100CEa92bE41d990670eD69c69f8e0',
	'Accept': 'application/json',
    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'
    }
    def __init__(self, api_Key, secret_key):
        self.url = 'http://47.104.165.120:8099/openapi' 
        self.api_Key = api_Key
        self.secret_key = secret_key
        
    def sign(self,params):
        params=copy.copy(params)
        now = int(time.time())*1000
        params['timestamp']= now
        sort_params = sorted(params.items(), key=operator.itemgetter(0))
        params = dict(sort_params)
        string = urllib.parse.urlencode(params)+'&'+self.secret_key
        sign = hashlib.md5(bytes(string.encode('utf-8'))).hexdigest().upper()
        params={}
        params['timestamp'] = now
        params['sign'] = sign
        return params
        
    def get(self,url,params):
        headers = dict(self._headers)
        postdata = urllib.parse.urlencode(params)
        try:
            response = requests.get(url, postdata, headers=headers, timeout=5)
            if response.status_code == 200:
                data = response.json()
                return data.get('data')
            else:
                print( {"status":"fail"},response.status_code)
        except Exception as e:
            print("httpGet failed, detail is:%s" %e)
            
    def get_sign(self,url,params):
        _headers = dict(self._headers)
        a = self.sign(params)
        params = dict(params,**a)
        postdata = json.dumps(params)
        # postdata = urllib.parse.urlencode(params)
        try:
            response = requests.get(url, postdata, headers=_headers, timeout=5)
            if response.status_code == 200:
                data = response.json()
                if data.get('code') !=  200 :
                    print(data.get('info'),data.get('code'))
                return data.get('data')
            else:
                print( {"status":"fail"},response.status_code)
        except Exception as e:
            print("httpGet failed, detail is:%s" %e)
        
    def postt(self,url,params):
        _headers = dict(self._headers)
        a = self.sign(params)
        params = dict(params,**a)
        postdata = json.dumps(params)
        # postdata = urllib.parse.urlencode(params)
        try:
            response = requests.post(url, postdata, headers=_headers, timeout=5)
            if response.status_code == 200:
                data = response.json()
                if data.get('code') !=  200 :
                    print(data.get('info'),data.get('code'))
                return data.get('data')
            else:
                print( {"status":"fail"},response.status_code)
        except Exception as e:
            print("httpGet failed, detail is:%s" %e)

    def get_balance(self,code,merchantId):
        params={}
        params['coinCode'] = code
        params['merchantId']=merchantId
        url =self.url + '/v1/asset/account'
        return self.postt(url,params)
        
    def get_currency_msg(self,symbol,merchantId):
        params={}
        params['symbol'] = symbol
        params['merchantId']=merchantId
        url =self.url + '/v1/exchange/rule'
        return self.get(url,params)
    
    def get_ticker(self,symbol,merchantId):
        params={}
        params['symbol'] = symbol
        params['merchantId']=merchantId
        url =self.url + '/v1/depth'
        return self.get(url,params)
    
    def take_order(self,entrustType,tradeAreaCurrencyEunit,tradePairCurrencyEunit,quantity,price,merchantId):
        params={}
        params['entrustType'] = entrustType
        params['tradeAreaCurrencyEunit'] = tradeAreaCurrencyEunit
        params['tradePairCurrencyEunit'] = tradePairCurrencyEunit
        params['quantity'] = quantity
        params['price'] = price
        params['merchantId']=merchantId
        url =self.url + '/v1/trade/order'
        return self.postt(url,params)
    
    def cancel_order(self,entrustId,merchantId):
        params={}
        params['entrustId'] = entrustId
        params['merchantId']=merchantId
        url =self.url + '/v1/trade/cancel'
        return self.postt(url,params)
    
    
        
        
        
            